<template>
  <j-modal
    title="执行领料"
    :width="1200"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel">
    
    <a-spin :spinning="confirmLoading">
      <a-descriptions title="基本信息" bordered :column="3">
        <a-descriptions-item label="领料单号">{{ model.requisitionNo }}</a-descriptions-item>
        <a-descriptions-item label="订单编号">{{ model.orderNo }}</a-descriptions-item>
        <a-descriptions-item label="优化软件类型">
          <a-tag :color="model.optimizationSoftwareType == '0' ? 'blue' : 'purple'">
            {{ model.optimizationSoftwareType == '0' ? '长风' : '新格尔' }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="领料日期">{{ model.requisitionDate }}</a-descriptions-item>
        <a-descriptions-item label="领料人">{{ model.requisitionPerson }}</a-descriptions-item>
        <a-descriptions-item label="备注">{{ model.remark || '-' }}</a-descriptions-item>
      </a-descriptions>
      
      <!-- 型材明细表格 -->
      <div v-if="showProfileTable">
        <div style="margin-top: 20px; margin-bottom: 10px;">
          <a-divider orientation="left">型材明细</a-divider>
        </div>
        
        <a-table
          ref="profileTable"
          size="middle"
          bordered
          rowKey="id"
          :columns="profileColumns"
          :dataSource="profileDataSource"
          :pagination="false">
          
          <template slot="statusSlot" slot-scope="text">
            <a-tag :color="text == '0' ? 'orange' : (text == '1' ? 'green' : 'blue')">
              {{ text == '0' ? '未领料' : (text == '1' ? '已领料' : '部分领料') }}
            </a-tag>
          </template>
          
          <template slot="quantitySlot" slot-scope="text, record, index">
            <a-input-number 
              v-if="record.status !== '1'"
              :min="0" 
              :max="record.quantity" 
              :precision="0"
              v-model="record.actualQuantity"
              style="width: 100px"
              @change="(value) => handleQuantityChange(value, record, index, 'profile')"
              placeholder="请输入数量"/>
            <span v-else>{{ record.actualQuantity || record.quantity }}</span>
          </template>
          
          <template slot="operationSlot" slot-scope="text, record, index">
            <a-checkbox 
              v-if="record.status !== '1'"
              v-model="record.checked"
              @change="(e) => handleCheckChange(e, record, index, 'profile')">
              领料
            </a-checkbox>
            <span v-else>已领料</span>
          </template>
          
        </a-table>
      </div>
      
      <!-- 配件明细表格 -->
      <div v-if="showAccessoryTable">
        <div style="margin-top: 20px; margin-bottom: 10px;">
          <a-divider orientation="left">配件明细</a-divider>
        </div>
        
        <a-table
          ref="accessoryTable"
          size="middle"
          bordered
          rowKey="id"
          :columns="accessoryColumns"
          :dataSource="accessoryDataSource"
          :pagination="false">
          
          <template slot="statusSlot" slot-scope="text">
            <a-tag :color="text == '0' ? 'orange' : (text == '1' ? 'green' : 'blue')">
              {{ text == '0' ? '未领料' : (text == '1' ? '已领料' : '部分领料') }}
            </a-tag>
          </template>
          
          <template slot="quantitySlot" slot-scope="text, record, index">
            <a-input-number 
              v-if="record.status !== '1'"
              :min="0" 
              :max="record.quantity" 
              :precision="0"
              v-model="record.actualQuantity"
              style="width: 100px"
              @change="(value) => handleQuantityChange(value, record, index, 'accessory')"
              placeholder="请输入数量"/>
            <span v-else>{{ record.actualQuantity || record.quantity }}</span>
          </template>
          
          <template slot="operationSlot" slot-scope="text, record, index">
            <a-checkbox 
              v-if="record.status !== '1'"
              v-model="record.checked"
              @change="(e) => handleCheckChange(e, record, index, 'accessory')">
              领料
            </a-checkbox>
            <span v-else>已领料</span>
          </template>
          
        </a-table>
      </div>
    </a-spin>
  </j-modal>
</template>

<script>
  import { getAction, postAction } from '@/api/manage'
  
  export default {
    name: 'RequisitionExecuteModal',
    data() {
      return {
        title: '执行领料',
        visible: false,
        model: {},
        confirmLoading: false,
        
        // 型材明细相关
        profileDataSource: [],
        showProfileTable: true,
        profileColumns: [
          { title: '型材编号', dataIndex: 'profileCode', align: 'center' },
          { title: '型材名称', dataIndex: 'profileName', align: 'center' },
          { title: '颜色', dataIndex: 'color', align: 'center' },
          { title: '长度(mm)', dataIndex: 'length', align: 'center' },
          { title: '宽度(mm)', dataIndex: 'width', align: 'center' },
          { title: '高度(mm)', dataIndex: 'height', align: 'center' },
          { title: '数量(根)', dataIndex: 'quantity', align: 'center' },
          { title: '领料状态', dataIndex: 'status', align: 'center', scopedSlots: { customRender: 'statusSlot' } },
          { title: '实际领料数量', dataIndex: 'actualQuantity', align: 'center', scopedSlots: { customRender: 'quantitySlot' } },
          { title: '操作', dataIndex: 'operation', align: 'center', scopedSlots: { customRender: 'operationSlot' } }
        ],
        
        // 配件明细相关
        accessoryDataSource: [],
        showAccessoryTable: true,
        accessoryColumns: [
          { title: '窗号', dataIndex: 'windowNo', align: 'center' },
          { title: '配件编号', dataIndex: 'accessoryCode', align: 'center' },
          { title: '配件名称', dataIndex: 'accessoryName', align: 'center' },
          { title: '规格', dataIndex: 'specification', align: 'center' },
          { title: '数量', dataIndex: 'quantity', align: 'center' },
          { title: '单位', dataIndex: 'unit', align: 'center' },
          { title: '领料状态', dataIndex: 'status', align: 'center', scopedSlots: { customRender: 'statusSlot' } },
          { title: '实际领料数量', dataIndex: 'actualQuantity', align: 'center', scopedSlots: { customRender: 'quantitySlot' } },
          { title: '操作', dataIndex: 'operation', align: 'center', scopedSlots: { customRender: 'operationSlot' } }
        ],
        
        url: {
          getRequisition: "/wms/requisition/queryById",
          getProfileList: "/wms/requisition/getProfileList",
          getAccessoryList: "/wms/requisition/getAccessoryList",
          execute: "/wms/requisition/executeRequisition"
        }
      }
    },
    methods: {
      show(id) {
        this.visible = true
        this.loadData(id)
      },
      
      loadData(id) {
        this.confirmLoading = true
        
        // 清空数据
        this.model = {}
        this.profileDataSource = []
        this.accessoryDataSource = []
        
        // 加载领料单数据
        getAction(`${this.url.getRequisition}?id=${id}`).then(res => {
          if (res.success) {
            this.model = res.result || {}
            
            // 根据优化软件类型调整表格显示和列
            this.adjustTablesByType(this.model.optimizationSoftwareType)
            
            // 加载型材明细
            this.loadProfileData(id)
            
            // 加载配件明细
            this.loadAccessoryData(id)
          }
        }).finally(() => {
          this.confirmLoading = false
        })
      },
      
      // 加载型材明细数据
      loadProfileData(requisitionId) {
        getAction(`${this.url.getProfileList}/${requisitionId}`).then(res => {
          if (res.success) {
            // 添加checked和actualQuantity字段
            this.profileDataSource = (res.result || []).map(item => {
              return {
                ...item,
                checked: item.status === '1',
                actualQuantity: item.status === '1' ? item.actualQuantity || item.quantity : 0
              }
            })
          }
        })
      },
      
      // 加载配件明细数据
      loadAccessoryData(requisitionId) {
        getAction(`${this.url.getAccessoryList}/${requisitionId}`).then(res => {
          if (res.success) {
            // 添加checked和actualQuantity字段
            this.accessoryDataSource = (res.result || []).map(item => {
              return {
                ...item,
                checked: item.status === '1',
                actualQuantity: item.status === '1' ? item.actualQuantity || item.quantity : 0
              }
            })
          }
        })
      },
      
      // 根据优化软件类型调整表格
      adjustTablesByType(type) {
        if (type === '0') { // 长风
          this.showProfileTable = true
          this.showAccessoryTable = true
          
          // 调整型材列
          this.profileColumns = [
            { title: '型材编号', dataIndex: 'profileCode', align: 'center' },
            { title: '型材名称', dataIndex: 'profileName', align: 'center' },
            { title: '颜色', dataIndex: 'color', align: 'center' },
            { title: '长度(mm)', dataIndex: 'length', align: 'center' },
            { title: '宽度(mm)', dataIndex: 'width', align: 'center' },
            { title: '高度(mm)', dataIndex: 'height', align: 'center' },
            { title: '数量(根)', dataIndex: 'quantity', align: 'center' },
            { title: '领料状态', dataIndex: 'status', align: 'center', scopedSlots: { customRender: 'statusSlot' } },
            { title: '实际领料数量', dataIndex: 'actualQuantity', align: 'center', scopedSlots: { customRender: 'quantitySlot' } },
            { title: '操作', dataIndex: 'operation', align: 'center', scopedSlots: { customRender: 'operationSlot' } }
          ]
          
          // 调整配件列
          this.accessoryColumns = [
            { title: '窗号', dataIndex: 'windowNo', align: 'center' },
            { title: '配件编号', dataIndex: 'accessoryCode', align: 'center' },
            { title: '配件名称', dataIndex: 'accessoryName', align: 'center' },
            { title: '规格', dataIndex: 'specification', align: 'center' },
            { title: '数量', dataIndex: 'quantity', align: 'center' },
            { title: '单位', dataIndex: 'unit', align: 'center' },
            { title: '领料状态', dataIndex: 'status', align: 'center', scopedSlots: { customRender: 'statusSlot' } },
            { title: '实际领料数量', dataIndex: 'actualQuantity', align: 'center', scopedSlots: { customRender: 'quantitySlot' } },
            { title: '操作', dataIndex: 'operation', align: 'center', scopedSlots: { customRender: 'operationSlot' } }
          ]
        } else if (type === '1') { // 新格尔
          this.showProfileTable = true
          this.showAccessoryTable = true
          
          // 调整型材列 (新格尔可能需要不同的列)
          this.profileColumns = [
            { title: '型材编号', dataIndex: 'profileCode', align: 'center' },
            { title: '型材名称', dataIndex: 'profileName', align: 'center' },
            { title: '数量(根)', dataIndex: 'quantity', align: 'center' },
            { title: '长度(mm)', dataIndex: 'length', align: 'center' },
            { title: '领料状态', dataIndex: 'status', align: 'center', scopedSlots: { customRender: 'statusSlot' } },
            { title: '实际领料数量', dataIndex: 'actualQuantity', align: 'center', scopedSlots: { customRender: 'quantitySlot' } },
            { title: '操作', dataIndex: 'operation', align: 'center', scopedSlots: { customRender: 'operationSlot' } }
          ]
          
          // 调整配件列 (新格尔可能需要不同的列)
          this.accessoryColumns = [
            { title: '配件编号', dataIndex: 'accessoryCode', align: 'center' },
            { title: '配件名称', dataIndex: 'accessoryName', align: 'center' },
            { title: '数量', dataIndex: 'quantity', align: 'center' },
            { title: '单位', dataIndex: 'unit', align: 'center' },
            { title: '领料状态', dataIndex: 'status', align: 'center', scopedSlots: { customRender: 'statusSlot' } },
            { title: '实际领料数量', dataIndex: 'actualQuantity', align: 'center', scopedSlots: { customRender: 'quantitySlot' } },
            { title: '操作', dataIndex: 'operation', align: 'center', scopedSlots: { customRender: 'operationSlot' } }
          ]
        }
      },
      
      // 处理数量变更
      handleQuantityChange(value, record, index, type) {
        // 如果输入数量大于0，自动勾选领料
        if (value > 0) {
          record.checked = true
        } else {
          record.checked = false
        }
      },
      
      // 处理勾选变更
      handleCheckChange(e, record, index, type) {
        const checked = e.target.checked
        
        // 如果勾选，但数量为0，则设置为最大数量
        if (checked && (!record.actualQuantity || record.actualQuantity === 0)) {
          record.actualQuantity = record.quantity
        }
        
        // 如果取消勾选，则数量设为0
        if (!checked) {
          record.actualQuantity = 0
        }
      },
      
      handleCancel() {
        this.visible = false
      },
      
      handleOk() {
        // 检查是否有选中的项目
        const selectedProfiles = this.profileDataSource.filter(item => item.checked && item.status !== '1')
        const selectedAccessories = this.accessoryDataSource.filter(item => item.checked && item.status !== '1')
        
        if (selectedProfiles.length === 0 && selectedAccessories.length === 0) {
          this.$message.warning('请至少选择一项进行领料!')
          return
        }
        
        // 检查选中的项目是否都填写了实际领料数量
        const invalidProfiles = selectedProfiles.filter(item => !item.actualQuantity || item.actualQuantity <= 0)
        const invalidAccessories = selectedAccessories.filter(item => !item.actualQuantity || item.actualQuantity <= 0)
        
        if (invalidProfiles.length > 0 || invalidAccessories.length > 0) {
          this.$message.warning('请为所有选中的项目填写实际领料数量!')
          return
        }
        
        this.confirmLoading = true
        
        // 构建提交数据
        const formData = {
          requisitionId: this.model.id,
          profiles: selectedProfiles.map(item => ({
            id: item.id,
            actualQuantity: item.actualQuantity
          })),
          accessories: selectedAccessories.map(item => ({
            id: item.id,
            actualQuantity: item.actualQuantity
          }))
        }
        
        // 发送请求
        postAction(this.url.execute, formData).then((res) => {
          if (res.success) {
            this.$message.success(res.message)
            this.$emit('ok')
            this.handleCancel()
          } else {
            this.$message.warning(res.message)
          }
        }).finally(() => {
          this.confirmLoading = false
        })
      }
    }
  }
</script>

<style scoped>
</style> 